<template>
  <div class="scene-management">
    <div class="header-bar">
      <h1 class="page-title">勤务场景管理</h1>
      <button class="btn btn-primary" @click="openAddModal">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
        <span>添加场景</span>
      </button>
    </div>

    <div class="table-container">
      <table>
        <thead>
        <tr>
          <th>场景编号</th>
          <th>场景名称</th>
          <th>描述</th>
          <th>关联警力需求</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-if="paginatedList.length === 0">
          <td colspan="5" class="empty-data">暂无数据</td>
        </tr>
        <tr v-for="scene in paginatedList" :key="scene.sceneId">
          <td>{{ scene.sceneNum }}</td>
          <td>{{ scene.sceneName }}</td>
          <td class="description-cell">{{ scene.description }}</td>
          <td>{{ scene.officeRequest }}</td>
          <td>
            <button class="btn-ai-scheduling" @click="generateAiScheduling(scene)">AI智能排班</button>
            <button class="btn-action btn-edit" @click="openEditModal(scene)">编辑</button>
            <button class="btn-action btn-delete" @click="deleteScene(scene.sceneId)">删除</button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 新增：分页组件 -->
    <Pagination
      v-if="sceneList.length > itemsPerPage"
      :current-page="currentPage"
      :total-pages="totalPages"
      @page-changed="handlePageChange"
    />

    <SceneFormModal
      v-if="isModalOpen"
      :is-edit-mode="isEditMode"
      :initial-data="selectedScene"
      @close="closeModal"
      @save="saveScene"
    />
    <ProgressModal
      v-if="isProgressModalOpen"
      :title="progressTitle"
      :message="progressMessage"
      :progress="progressValue"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import SceneFormModal from './SceneFormModal.vue';
import Pagination from '@/components/Pagination.vue';
import api from '@/utils/axios';
import { useRouter } from 'vue-router';
import ProgressModal from "@/components/common/ProgressModal.vue";

const API_BASE_URL = 'http://localhost:8080/api/auth';
const sceneList = ref<any[]>([]);
const router = useRouter();
const officers = ref<any[]>([]);

// --- 分页逻辑 ---
const currentPage = ref(1);
const itemsPerPage = ref(10);
const totalPages = computed(() => Math.ceil(sceneList.value.length / itemsPerPage.value));

const paginatedList = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  const end = start + itemsPerPage.value;
  return sceneList.value.slice(start, end);
});

// 进度条弹窗逻辑
const isProgressModalOpen = ref(false);
const progressTitle = ref('');
const progressMessage = ref('');
const progressValue = ref(0);
let progressInterval: any = null;

const startProgress = () => {
  isProgressModalOpen.value = true;
  progressValue.value = 0;
  progressTitle.value = '正在生成AI建议';
  progressMessage.value = '系统正在分析数据，请稍候...';
  progressInterval = setInterval(() => {
    if (progressValue.value < 95) {
      progressValue.value += Math.random() * 5;
    }
  }, 300);
};

const finishProgress = () => {
  clearInterval(progressInterval);
  progressValue.value = 100;
  progressTitle.value = '生成成功';
  progressMessage.value = '即将跳转到排班管理页面...';
  setTimeout(() => {
    isProgressModalOpen.value = false;
    router.push('/admin/scheduling');
  }, 1000);
};

const failProgress = (errorMsg: string) => {
  clearInterval(progressInterval);
  isProgressModalOpen.value = false;
  alert(errorMsg);
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
};

// --- 弹窗及数据操作逻辑 ---
const isModalOpen = ref(false);
const isEditMode = ref(false);
const selectedScene = ref<any>(null);

const openAddModal = () => { isEditMode.value = false; selectedScene.value = null; isModalOpen.value = true; };
const openEditModal = (scene: any) => { isEditMode.value = true; selectedScene.value = { ...scene }; isModalOpen.value = true; };
const closeModal = () => { isModalOpen.value = false; };

const saveScene = async (data: any) => {
  if (isEditMode.value) {
    const index = sceneList.value.findIndex(s => s.sceneId === data.sceneId);
    if (index !== -1) sceneList.value[index] = data;
  } else {
    sceneList.value.unshift(data);
    currentPage.value = 1;
  }
  closeModal();
};

const deleteScene = async (sceneId: number) => {
  if (confirm(`确定要删除场景 ${sceneId} 吗？`)) {
    try {
      await api.delete(`${API_BASE_URL}/deleteScene/${sceneId}`);
      sceneList.value = sceneList.value.filter(s => s.sceneId !== sceneId);
      if (paginatedList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--;
      }
    } catch (error) {
      console.error('删除场景出错:', error);
      alert('删除场景出错，请稍后重试！');
    }
  }
};

const fetchScenes = async () => {
  try {
    const response = await api.get(`${API_BASE_URL}/scenes`);
    sceneList.value = response.data;
  } catch (error) {
    console.error('获取场景列表出错:', error);
    alert('获取场景列表出错，请稍后重试！');
  }
};

// 获取所有警员信息
const getOfficers = async () => {
  try {
    const response = await api.get(`${API_BASE_URL}/officers`);
    officers.value = response.data.data || [];

    // 打印获取到的警员信息
    console.groupCollapsed('【获取到的警员信息】');
    console.log('警员数量:', officers.value.length);
    if (officers.value.length > 0) {
      console.log('前3名警员信息:', officers.value.slice(0, 3));
    }
    console.groupEnd();
  } catch (error) {
    console.error('获取警员信息出错:', error);
    alert('获取警员信息出错，请稍后重试！');
  }
};

const generateAiScheduling = async (scene: any) => {
  startProgress();
  try {
    // 先获取警员信息
    await getOfficers();

    // 将场景和警员信息一起发送给后端
    const requestData = {
      scene,
      officers: officers.value
    };

    // 打印发送到后端的数据
    console.groupCollapsed('【发送到AI接口的数据】');
    console.log('场景信息:', scene);
    console.log('警员信息数量:', officers.value.length);
    if (officers.value.length > 0) {
      console.log('前3名警员信息:', officers.value.slice(0, 3));
    }
    console.log('完整请求数据:', requestData);
    console.groupEnd();

    const response = await api.post('http://localhost:8080/generateSchedulingSuggestion', requestData,{ timeout: 180000 });
    localStorage.setItem('aiSuggestions', JSON.stringify(response.data));
    finishProgress();
    router.push('/admin/scheduling');
  } catch (error) {
    console.error('生成 AI 排班建议出错:', error);
    failProgress('生成 AI 排班建议出错，请稍后重试！');
    alert('生成 AI 排班建议出错，请稍后重试！');
  }
};

onMounted(() => {
  fetchScenes();
});
</script>

<style scoped>
@import "@/assets/styles/views/admin/SceneManagement.css";
</style>
